Vue.component('user-management', {
  data() {
    return {
      users: [],
      loading: false,
      searchForm: {
        username: '',
        status: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        username: '',
        password: '',
        role: 'operator',
        name: '',
        gender: '',
        birth_date: '',
        phone: '',
        email: '',
        address: ''
      },
      formRules: {
        username: [
          { required: function() { return !this.formData.id; }, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: function() { return !this.formData.id; }, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      roles: [
        { value: 'admin', label: '管理员' },
        { value: 'operator', label: '操作员' }
      ],
      genders: [
        { value: 'male', label: '男' },
        { value: 'female', label: '女' }
      ],
      resetPasswordDialog: false,
      resetPasswordForm: {
        userId: null,
        newPassword: '',
        confirmPassword: ''
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    async loadUsers() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize
        };
        
        // 处理搜索参数
        if (this.searchForm.username) {
          params.username = this.searchForm.username;
        }
        if (this.searchForm.status) {
          params.status = this.searchForm.status;
        }
        
        const response = await userAPI.getUsers(params);
        if (response.data && response.data.users) {
          this.users = response.data.users;
          this.total = response.data.pagination.total;
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error(error.message || '获取用户列表失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadUsers();
    },
    handleReset() {
      this.searchForm = {
        username: '',
        status: ''
      };
      this.currentPage = 1;
      this.loadUsers();
    },
    handleAdd() {
      this.dialogTitle = '添加操作员';
      this.formData = {
        id: null,
        username: '',
        password: '',
        role: 'operator',
        name: '',
        gender: '',
        birth_date: '',
        phone: '',
        email: '',
        address: ''
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑操作员';
      this.formData = { ...row };
      // 编辑时清空密码字段，因为不需要修改密码
      this.formData.password = '';
      this.dialogVisible = true;
    },
    async handleSubmit() {
      try {
        console.log('开始验证表单...');
        await this.$refs.form.validate();
        console.log('表单验证通过');
        
        if (this.formData.id) {
          // 编辑用户 - 不包含密码字段
          const updateData = { ...this.formData };
          delete updateData.password; // 编辑时不发送密码
          console.log('编辑用户数据:', updateData);
          await userAPI.updateUser(this.formData.id, updateData);
          this.$message.success('操作员信息更新成功');
        } else {
          // 创建用户
          console.log('创建用户数据:', this.formData);
          const response = await userAPI.createUser(this.formData);
          console.log('创建用户响应:', response);
          this.$message.success('操作员创建成功');
        }
        
        this.dialogVisible = false;
        this.loadUsers();
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(error.message || '操作失败');
      }
    },
    handleDelete(row) {
      this.$confirm('确定要删除该操作员吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await userAPI.deleteUser(row.id);
          this.$message.success('删除成功');
          this.loadUsers();
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error(error.message || '删除失败');
        }
      });
    },
    handleResetPassword(row) {
      this.resetPasswordForm = {
        userId: row.id,
        newPassword: '',
        confirmPassword: ''
      };
      this.resetPasswordDialog = true;
    },
    async handleResetPasswordSubmit() {
      try {
        await this.$refs.resetPasswordForm.validate();
        
        await userAPI.resetPassword(this.resetPasswordForm.userId, this.resetPasswordForm.newPassword);
        this.$message.success('密码重置成功');
        this.resetPasswordDialog = false;
      } catch (error) {
        console.error('密码重置失败:', error);
        this.$message.error(error.message || '密码重置失败');
      }
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.resetPasswordForm.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadUsers();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadUsers();
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString();
    },
    getRoleLabel(role) {
      const roleObj = this.roles.find(r => r.value === role);
      return roleObj ? roleObj.label : role;
    },
    getGenderLabel(gender) {
      const genderObj = this.genders.find(g => g.value === gender);
      return genderObj ? genderObj.label : gender;
    }
  },
  async mounted() {
    await this.loadUsers();
  },
  template: `
    <div class="user-management">
      <el-card>
        <div slot="header">
          <span>操作员管理</span>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;" size="small">
            添加操作员
          </el-button>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 用户表格 -->
        <el-table :data="users" v-loading="loading" border>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80">
            <template slot-scope="scope">
              {{ getGenderLabel(scope.row.gender) }}
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" width="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" min-width="150"></el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="150">
            <template slot-scope="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" style="color: #e6a23c;" @click="handleResetPassword(scope.row)">重置密码</el-button>
              <el-button type="text" style="color: #f56c6c;" @click="handleDelete(scope.row)" v-if="scope.row.role !== 'admin'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;">
        </el-pagination>
      </el-card>
      
      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form :model="formData" :rules="formRules" ref="form" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="formData.username" placeholder="请输入用户名" :disabled="!!formData.id"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!formData.id">
              <el-form-item label="密码" prop="password">
                <el-input v-model="formData.password" type="password" placeholder="请输入密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%;">
                  <el-option
                    v-for="item in genders"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期">
                <el-date-picker
                  v-model="formData.birth_date"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="地址">
            <el-input type="textarea" v-model="formData.address" placeholder="请输入地址" :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
      
      <!-- 重置密码对话框 -->
      <el-dialog title="重置密码" :visible.sync="resetPasswordDialog" width="400px">
        <el-form :model="resetPasswordForm" :rules="resetPasswordRules" ref="resetPasswordForm" label-width="100px">
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="resetPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handleResetPasswordSubmit">确定</el-button>
        </div>
      </el-dialog>
    </div>
  `
});
